import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:sl_flutter/utils/http.dart';
import 'package:sl_flutter/utils/tokenManager.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  var token = '1';

  bool obscureText = true;

  void _submitLogin(String username, String password) async {
    try {
      final res = await https.post(
          '/driver/login/account', {"account": username, "password": password});
      print('登录响应: $res'); // 打印响应结果，方便调试
      token = res['data'];
      // 持久化token
      await TokenManager().saveToken(token);

      if (res['code'] == 200) {
        if (context.mounted) {
          Navigator.pushReplacementNamed(context, '/tabs');
        }
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Center(
            child: Text('登陆成功'),
          ),
          width: 100,
          duration: Duration(seconds: 1),
          backgroundColor: Colors.green,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(50), // 设置圆角半径
          ),
        ));
      } else {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Center(
            child: Text('登陆失败'),
          ),
          width: 100,
          duration: Duration(seconds: 1),
          backgroundColor: Colors.red,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(50), // 设置圆角半径
          ),
        ));
      }
    } catch (e) {
      print('登录请求出错: $e'); // 打印具体的错误信息
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Center(
          child: Text('登陆失败'),
        ),
        width: 100,
        duration: Duration(seconds: 1),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(50), // 设置圆角半径
        ),
      ));
    }

    print(token);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        // 取消顶部返回按钮
        automaticallyImplyLeading: false,
        backgroundColor: Colors.white,
        title: const Text(
          '神领快递',
          style: TextStyle(fontWeight: FontWeight.w600),
        ),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(30),
        child: Center(
            child: Container(
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '账号登录',
                    style: TextStyle(fontWeight: FontWeight.w900, fontSize: 28),
                  ),
                  Text(
                    '手机号登录 ->',
                    style: TextStyle(
                        fontWeight: FontWeight.w700,
                        fontSize: 15,
                        color: Colors.deepOrange),
                  ),
                ],
              ),
              Column(
                children: [
                  Padding(padding: const EdgeInsets.only(top: 40)),
                  TextField(
                    controller: usernameController,
                    decoration: InputDecoration(
                      labelText: '请输入账号',
                    ),
                    onChanged: (value) {
                      // print('输入的内容是: $value');
                    },
                  ),
                  Padding(padding: const EdgeInsets.only(top: 20)),
                  TextField(
                    obscureText: obscureText, // 设置为 true 以加密显示
                    controller: passwordController,
                    decoration: InputDecoration(
                      labelText: '请输入密码',
                      suffixIcon: IconButton(
                        icon: obscureText
                            ? Icon(Icons.visibility_off)
                            : Icon(Icons.remove_red_eye_outlined),
                        onPressed: () {
                          setState(() {
                            obscureText = !obscureText; // 切换密码可见状态
                          });
                        },
                      ),
                    ),
                    onChanged: (value) {
                      // print('输入的内容是: $value');
                    },
                  ),
                  const SizedBox(height: 40),
                  ElevatedButton(
                    onPressed: () {
                      String username = (usernameController.text);
                      String password = (passwordController.text);
                      // print('用户名: $username, 密码: $password');
                      _submitLogin(username, password);
                    },
                    child: Text(
                      '登录',
                      style: TextStyle(color: Colors.white),
                    ),
                    style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.deepOrange,
                        minimumSize: const Size(300, 50)),
                  ),
                ],
              )
            ],
          ),
        )),
      ),
    );
  }
}
